<?php
class UsersController extends AppController {

	var $components = array('Captcha', 'Email');
	var $name = 'Users';

	function beforeFilter() {
		parent::beforeFilter();
		$this->Auth->fields = array('username' => 'login', 'password' => 'passwd');
	}

	function index() {
//		$res =	$this->User->find('all');
//pr($res);
		pr($this->Auth->user());
	}


	function login() {

	}

        function logout() {
		$this->Auth->logout();
                $this->redirect('/');
        }

	function register() {
		if(!empty($this->data['User'])) {
			$this->User->create();
			$this->User->set($this->data);
			if($this->User->validates()) {
				$this->data['User']['uuid'] = String::uuid();
				$this->data['User']['passwd'] = $this->Auth->password($this->data['User']['password']);
				if($this->User->save($this->data)) {
					$mail['to']	= $this->data['User']['email'];	
					$mail['from']	= 'nester@bk.ru';
					$mail['subject'] = 'Регистрация';
					$mail['text'][] = 'Здравствуйте, Вы зарегистрировалась на '. $_SERVER['HTTP_HOST'];
					$mail['text'][] = '';
					$mail['text'][] = 'Логин: ' . $this->data['User']['login'];
					$mail['text'][] = 'Пароль: ' . $this->data['User']['password'];
					$mail['text'][] = '';
					$mail['text'][] = 'Подтверждение электронной почты, пройдите по ниже написанной ссылке:';
					$mail['text'][] = 'http://'.$_SERVER['HTTP_HOST'].'/users/mailconfirm/'.$this->data['User']['login'].'/'. $this->data['User']['uuid'].'/';

					$this->__sendMail($mail);

					$this->Session->setFlash(__('register_successful', true));
					$this->Auth->login($this->data);
					$this->redirect($this->Auth->redirect());
				}
			}
		}
	}

	function captcha() {
		header("Cache-Control: no-cache, must-revalidate");
		header("Pragma: no-cache");
		header("Expires: -1;");
		$this->Captcha->image();
	}

	function mailconfirm($login = null, $uuid = null) {
		$confirm = false;
		if ($login && $uuid) {
			$c = array('login'=>$login);
			$f = array('id', 'mailconfirm', 'uuid');
			$this->User->unBindModel(array('hasOne'=>array('Profile')));
			$mail = $this->User->find('first', array('conditions'=>$c, 'fields'=>$f));
			$mail = $mail['User'];
//pr($mail);
		
			if (!$mail['mailconfirm']) {
				if ($uuid === $mail['uuid']) {
					$this->User->id = $mail['id'];
					$dataS['mailconfirm'] = 1;
					$dataS['uuid'] = String::uuid();
					if ($this->User->save($dataS)) {
						$confirm = true;
					}
				}
			} else {
				$confirm = true;
			}
		}

		if ($confirm) {
			$this->Session->setFlash(__('mailconfirm_successful', true));
		}
	}

	function restorepassword($login = null, $uuid = null) {
		if (isset($this->data)) {
			$this->User->set($this->data);
			if ($this->User->validates()) {
				$uData = $this->data['User']['restore'];

				if (ereg('^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$', $uData)) {
					$field = 'email';
				} else {
					$field = 'login';
				}
			
				$u = $this->User->find('first', array('conditions'=>array($field=>$uData), 'fields'=>array('id', 'login', 'email')));

				if ($u) {
					$uuid = String::uuid();
					$this->User->id = $u['User']['id'];
					if ($this->User->saveField('uuid', $uuid)) {

						$mail['to']	= $u['User']['email'];	
						$mail['from']	= 'nester@bk.ru';
						$mail['subject'] = 'Востановление пароля';
						$mail['text'][] = 'Востоновить пароль? Если да, то пройдите по ссылке ниже:';
						$mail['text'][] = 'http://'.$_SERVER['HTTP_HOST'].'/users/restorepassword/'.$u['User']['login'].'/'. $uuid.'/';

						if ($this->__sendMail($mail)) {
							$this->Session->setFlash('Ссылка на востановление пароля была выслана на почтовый адрес');
						}

					}

				} else {
					$this->Session->setFlash(__('loginmailmiss', true));
				}
			}
		}

		if ($login && $uuid) {
			$u = $this->User->loginUuid($login, $uuid);
			if ($u) {

				srand((double)microtime()*1000000);
				$chars = 'qwertyuiopasdfghjklzxcvbnm';
				$pass = '';
				for ($i = 0; $i < 5; $i++) {
					$num = rand() % 26;
					$tmp = substr($chars, $num, 1);
					$pass = $pass . $tmp;
				}

				$pass = $pass . rand(00, 99);

				$this->User->id = $u['id'];
				$dataS['uuid'] = String::uuid();
				$dataS['passwd'] = $this->Auth->password($pass);

				if ($this->User->save($dataS)) {
			

					$mail['to']	= $u['email'];	
					$mail['from']	= 'nester@bk.ru';
					$mail['subject'] = 'Востановленный пароль';
					$mail['text'][] = 'Здравствуйте, Ваш новый пароль:';
					$mail['text'][] = '';
					$mail['text'][] = 'Логин: ' . $u['login'];
					$mail['text'][] = 'Пароль: ' . $pass;
					$mail['text'][] = '';

					if ($this->__sendMail($mail)) {
						$this->Session->setFlash('новый пароль отправлен на Ваш почтовый ящик');
					}
				}

				
			}
		}

	}

	function __sendMail($mail = array()) {
		$this->Email->delivery          = 'smtp';
		$this->Email->smtpOptions	= array('port'=>25, 'host'=>'localhost');
		$this->Email->to                = $mail['to'];
		$this->Email->from		= $mail['from'];
		$this->Email->headers[]         = 'Content-Type: text/plain; charset="UTF-8"';
		$this->Email->subject           = $mail['subject'];
		$this->Email->lineLength        = 256;

		return $this->Email->send($mail['text']);
	}
}
